var App = new Object();
(function(root, factory) {
	if(typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if(typeof module === 'object' && module.exports) {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = App();
	} else {
		// Browser globals (root is window)
		root.App = factory();
	}
}(this, function() {
	var viewRouteMap = new Object();;
	var init = function() {
		if(window.plus) {
			plusReady();
		} else {
			document.addEventListener('plusready', plusReady, false);
		}
	}

	var getImmersed = function() {
		var immersed = 0;
		var ms = (/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);
		if(ms && ms.length >= 3) { // 当前环境为沉浸式状态栏模式
			immersed = parseFloat(ms[2]); // 获取状态栏的高度
		}
		return immersed;
	}

	var navigatorTo = function(conf) {
		mui.fire(plus.webview.getLaunchWebview(), 'openView', conf);
	}

	var checkLogin = function(cb) {
		var userInfo = JSON.parse(localStorage.userInfo); 
		if(userInfo.token == '' || userInfo.token == undefined || !(userInfo.expiretime > (Date.parse(new Date()) / 1000))) {
			App.navigatorTo({
				url: 'login.html',
				id: 'login',
			})
		} else {
			if(typeof(cb) == 'function') {
				cb(userInfo);
			}
			return true
		}

	}

	var commandToGetNewUserInfo = function() {
		var allWebviewList = plus.webview.all();
		for(var i = 0, len = allWebviewList.length; i < len; i++) {
			mui.fire(allWebviewList[i], 'userInfoRefreshed', {
				userInfo: JSON.parse(localStorage.userInfo)
			});
		}
	}

	var plusReady = function() {
		if(plus.webview.currentWebview().id == plus.runtime.appid) {
			document.addEventListener('openView', function(e) {
				openView(e.detail);
			}, false);
			document.addEventListener('closeView', function(e) {
				closeView(e.detail.webviewId);
			}, false);
		} else {
			mui.back = function() {
				mui.fire(plus.webview.getLaunchWebview(), 'closeView', {
					webviewId: plus.webview.currentWebview().id
				});
				return false;
			}
		}
	}

	var openView = function(conf) {
		var webviewId = conf.id;
		if(viewRouteMap[webviewId] !== undefined) {
			viewRouteMap[webviewId].close('none');
			delete viewRouteMap[webviewId];
		}
		viewRouteMap[webviewId] = mui.openWindow(conf)
	}

	var closeView = function(webviewId) {
		if(viewRouteMap[webviewId] !== undefined) {
			viewRouteMap[webviewId].close();
			delete viewRouteMap[webviewId];
		}
	}

	return {
		init: init,
		getImmersed: getImmersed,
		navigatorTo: navigatorTo,
		checkLogin: checkLogin,
		commandToGetNewUserInfo: commandToGetNewUserInfo
	}
}))